import React, {Component} from 'react';
import Frisbee from 'frisbee';
import MD5 from 'md5-es';
import RNFetchBlob from 'rn-fetch-blob';
import AsyncStorage from '@react-native-community/async-storage';
import {Actions} from 'react-native-router-flux';

import {showToast} from './utils';

class Api {
  constructor() {
    this.init();
  }

  init() {
    //this.baseURI = 'https://www.shyuezheng.com/app/supplier';
    this.baseURI = 'http://115.238.44.219:8000/app/supplier';
    this.SOCKET_URL = 'http://www.shyuezheng.com:8088';

    const headers = {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    };
    if (this.token) headers.Authorization = 'Bearer ' + this.token;

    this.api = new Frisbee({
      baseURI: this.baseURI,
      headers,
      logRequest: (path, options) => {
        // console.log(path, options);
      },
    });
    this.api.interceptor.register({
      response: async response => {
        try {
          const username = await AsyncStorage.getItem('@username');
          const password = await AsyncStorage.getItem('@password');
          const {status, body} = response;
          if (status !== 200) {
            console.log(response);
            if (status !== 401) {
              showToast(body.message || '网络请求错误');
            } else if (status == 401 && Actions.currentScene != 'login') {
              if (username) {
                const data = await this.login(username, password);
                if (data.status == 200) {
                  Actions.replace(Actions.currentScene, data.body);
                }
              } else {
                this.logout();
              }
            }
          }
          return response;
        } catch (error) {
          console.log(error);
          showToast('网络请求异常');
        }
      },
    });
  }

  logout() {
    AsyncStorage.removeItem('@username');
    AsyncStorage.removeItem('@password');
    AsyncStorage.removeItem('@loginUser');
    this.token = '';
    Actions.login();
    this.init();
  }

  login(username, password) {
    return this.api
      .post('/login', {
        body: {
          username,
          password: MD5.hash(password),
        },
      })
      .then(data => {
        if (data.status == 200) {
          this.token = data.body.token;
          AsyncStorage.setItem('@loginUser', JSON.stringify(data.body));
          AsyncStorage.setItem('@username', username);
          AsyncStorage.setItem('@password', password);
          this.api.setOptions({
            headers: {
              Authorization: 'Bearer ' + data.body.token,
              'Content-Type': 'application/json',
            },
          });
        }
        return data;
      })
      .catch(e => {
        console.log(e);
      });
  }

  worksheet(status, page) {
    return this.api
      .get('/workorder', {
        body: {
          status,
          page,
        },
      })
      .then(data => data.body);
  }

  worksheetLog(orderId) {
    return this.api
      .get('/workorderlog', {
        body: {
          orderId,
        },
      })
      .then(data => data.body);
  }

  worksheetcount() {
    return this.api.get('/workorderbystatus').then(data => data.body);
  }

  getStatus(status) {
    switch (status) {
      case 100:
        return '创建';
      case 200:
        return '派单';
      case 201:
        return '服务商拒单';
      case 300:
        return '服务商接单';
      case 400:
        return '到场(维修中)';
      case 401:
        return '退回';
      case 500:
        return '回单';
      case 600:
        return '结单';
      case 700:
        return '结束';
    }
  }

  nextStatus(status) {
    switch (status) {
      case 100:
        return [200];
      case 200:
        return [300, 201];
      case 201:
        return [];
      case 300:
        return [400, 401];
      case 400:
        return [500, 600];
      case 401:
        return [];
      case 500:
        return [500, 600, 401];
      case 600:
        return [];
      default:
        return [];
    }
  }

  getProcessibel(status) {
    return status == 400 || status == 500; //到场与回单中
  }

  uploadPhoto(file) {
    file.data = 'RNFetchBlob-' + file.uri;
    return RNFetchBlob.fetch(
      'POST',
      this.baseURI + '/pictures',
      {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data',
        Authorization: 'Bearer ' + this.token,
      },
      [file],
    ).then(data => {
      const json = data.json();
      if (json.status == 401 && Actions.currentScene != 'login') {
        Actions.login();
      }
      return json;
    });
  }

  photo(url) {
    return {
      uri: this.baseURI + '/picture/' + url,
      headers: {
        Authorization: 'Bearer ' + this.token,
      },
    };
  }

  addAccident(data) {
    return this.api
      .post('/addAccident', {
        body: data,
      })
      .then(res => res.body);
  }

  customerinfo(code) {
    return this.api
      .get('/customerinfo', {
        body: {
          code,
        },
      })
      .then(res => res.body);
  }

  equipmentinfo(code, customerId) {
    return this.api
      .get('/equipmentinfo', {
        body: {
          code,
          customerId,
        },
      })
      .then(res => res.body);
  }

  workorderprocess(orderId, content, orderStatus) {
    return this.api
      .post('workorderprocess', {
        body: {
          orderId,
          content,
          orderStatus,
        },
      })
      .then(res => res);
  }

  dictDetail(id) {
    return this.api
      .get('/dictdetail', {
        body: {
          id,
        },
      })
      .then(data => data.body);
  }

  getDeviceNames(id) {
    return this.api
      .get('/devicenames', {
        body: {
          id,
        },
      })
      .then(data => data.body);
  }

  changePassword({newPass, password}) {
    return this.api
      .post('/reset', {
        body: {
          newPass: MD5.hash(newPass),
          password: MD5.hash(password),
        },
      })
      .then(res => res);
  }

  getUserInfo() {
    return this.api
      .get('/userinfo', {
        body: {},
      })
      .then(data => data.body);
  }
  /**
   * 获取国家、省市区数据
   * 所有国家：api/tRegion?pid=0，id为1是中国
   * 国家下的省：api/tRegion?pid=1，这个id是国家的id
   * 省下面的市：api/tRegion?pid=46982，这个id是省的id
   * 市下面的区：api/tRegion?pid=53862，这个id是市的id
   */
  getRegion(pid) {
    return this.api
      .get('/tRegion', {
        body: {
          pid,
          size: 9999,
        },
      })
      .then(data => data.body);
  }
  /**
   * 重置密码
   */
  resetPassword(data = {}) {
    return this.api
      .post('/resetpassword', {
        body: {
          ...data,
        },
      })
      .then(data => data.body);
  }
  /**
   * 重新绑定号码
   */
  rebind(data = {}) {
    return this.api
      .post('/rebind', {
        body: {
          ...data,
        },
      })
      .then(data => data.body);
  }
  /**
   * 注册
   */
  register(data = {}) {
    return this.api
      .post('/register', {
        body: {
          ...data,
        },
      })
      .then(data => data.body);
  }
  /**
   * 发送短信验证码
   */
  getCaptcha(cellphone) {
    return this.api
      .get('/captcha', {
        body: {
          cellphone,
        },
      })
      .then(data => data.body);
  }
  /**
   * 根据邀请码查企业
   */
  byInviteCode(inviteCode) {
    return this.api
      .get('/byInviteCode', {
        body: {
          inviteCode,
        },
      })
      .then(data => data.body);
  }
}

export default new Api();
